/** 
* @author: 谢明霁
* @date：2017年7月9日 下午3:13:28
* @version 1.0 
*/
package dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.query.Query;

import bean.User;

public class MultiPropertyDao {
	// value[i]为第i个查询条件propertyName[i]的值 （本方法已通过测试）

	/*
	 * 多条件查询,查询条件的值为空时自动除去该条件 rigor为true时采用精确查询
	 */
	public List searchByPropertys(String bean, String[] propertyName, Object[] value, boolean rigor) {
		StringBuilder sqlBuilder = new StringBuilder();
		String ralation = " like ";
		if (rigor) {
			ralation = " = ";
		}
		sqlBuilder.append("from " + bean + " as model\n");
		int len = propertyName.length;
		List result = new ArrayList();
		boolean first = true;
		for (int i = 0; i < len; i++) {
			if (value[i] != null) {
				if (first) {
					sqlBuilder.append(" where " + "model." + propertyName[i] + ralation + " ?\n");
					result.add(value[i]);
					first = false;
				} else {
					sqlBuilder.append(" and " + "model." + propertyName[i] + ralation + " ?\n");
					result.add(value[i]);
				}
			}
		}

		try {
			Session session = DaoUtil.getSession();
			Query queryObject = session.createQuery(sqlBuilder.toString());
			for (int i = 0; i < result.size(); i++) {
				if (rigor) {
					queryObject.setParameter(i, result.get(i));
				} else {
					queryObject.setParameter(i, "%" + result.get(i) + "%");
				}

			}

			result = queryObject.list();

		} catch (RuntimeException e) {
			throw e;
		}
		return result;
	}

	public static void main(String[] args) {
		String[] propertyName = { "userName", "sex" };
		String[] value = { "bdx", "男" };
		final List searchByPropertys = new MultiPropertyDao().searchByPropertys("User", propertyName, value, true);
		for (Object user : searchByPropertys) {
			if(user instanceof User){
				System.out.println(((User)user).getUserName());
			}
		}
	}
}
